//package com.demo.apparel.utils;
//
//import com.demo.apparel.config.COSProperties;
//import com.qcloud.cos.COSClient;
//import com.qcloud.cos.model.DeleteObjectRequest;
//import com.qcloud.cos.model.ObjectMetadata;
//import com.qcloud.cos.model.PutObjectRequest;
//import org.springframework.stereotype.Component;
//import org.springframework.web.multipart.MultipartFile;
//
//import java.io.File;
//import java.io.FileInputStream;
//import java.util.UUID;
//
//@Component
//public class COSUploadUtils {
//
//    private final COSClient cosClient;
//    private final COSProperties properties;
//
//    public COSUploadUtils(COSClient cosClient, COSProperties properties) {
//        this.cosClient = cosClient;
//        this.properties = properties;
//    }
//
//    /** 上传 MultipartFile */
//    public String upload(MultipartFile file, String folder) {
//        try {
//            String fileName = folder + "/" + UUID.randomUUID() + "_" + file.getOriginalFilename();
//
//            ObjectMetadata metadata = new ObjectMetadata();
//            metadata.setContentLength(file.getSize());
//
//            // 设置 ContentType
//            String contentType = file.getContentType();
//            if (contentType == null || "application/octet-stream".equals(contentType)) {
//                contentType = getContentType(file.getOriginalFilename());
//            }
//            metadata.setContentType(contentType);
//            metadata.setHeader("Content-Disposition", "inline");
//
//            cosClient.putObject(new PutObjectRequest(
//                    properties.getBucketName(),
//                    fileName,
//                    file.getInputStream(),
//                    metadata
//            ));
//
//            return String.format("https://%s.cos.%s.myqcloud.com/%s",
//                    properties.getBucketName(),
//                    properties.getRegion(),
//                    fileName);
//        } catch (Exception e) {
//            throw new RuntimeException("文件上传失败", e);
//        }
//    }
//
//    /** 上传本地文件 */
//    public String upload(File localFile, String folder) {
//        try {
//            String fileName = folder + "/" + UUID.randomUUID() + "_" + localFile.getName();
//
//            ObjectMetadata metadata = new ObjectMetadata();
//            metadata.setContentLength(localFile.length());
//
//            String contentType = getContentType(localFile.getName());
//            metadata.setContentType(contentType);
//            metadata.setHeader("Content-Disposition", "inline");
//
//            cosClient.putObject(new PutObjectRequest(
//                    properties.getBucketName(),
//                    fileName,
//                    new FileInputStream(localFile),
//                    metadata
//            ));
//
//            return String.format("https://%s.cos.%s.myqcloud.com/%s",
//                    properties.getBucketName(),
//                    properties.getRegion(),
//                    fileName);
//        } catch (Exception e) {
//            throw new RuntimeException("文件上传失败", e);
//        }
//    }
//
//    /** 删除文件 */
//    public void delete(String fileKey) {
//        try {
//            DeleteObjectRequest deleteObjectRequest =
//                    new DeleteObjectRequest(properties.getBucketName(), fileKey);
//            cosClient.deleteObject(deleteObjectRequest);
//        } catch (Exception e) {
//            throw new RuntimeException("删除文件失败: " + fileKey, e);
//        }
//    }
//
//    /** 根据文件后缀推断 ContentType */
//    private String getContentType(String filename) {
//        if (filename == null || !filename.contains(".")) return "application/octet-stream";
//        String ext = filename.substring(filename.lastIndexOf(".")).toLowerCase();
//        switch (ext) {
//            case ".jpg":
//            case ".jpeg": return "image/jpeg";
//            case ".png":  return "image/png";
//            case ".gif":  return "image/gif";
//            case ".webp": return "image/webp";
//            case ".svg":  return "image/svg+xml";
//            case ".pdf":  return "application/pdf";
//            case ".mp4":  return "video/mp4";
//            case ".mp3":  return "audio/mpeg";
//            default:      return "application/octet-stream";
//        }
//    }
//}


package com.demo.apparel.utils;

import com.demo.apparel.config.COSProperties;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.DeleteObjectRequest;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Component
public class COSUploadUtils {

    private final COSClient cosClient;
    private final COSProperties properties;

    public COSUploadUtils(COSClient cosClient, COSProperties properties) {
        this.cosClient = cosClient;
        this.properties = properties;
    }

    /** 上传 MultipartFile */
    public String upload(MultipartFile file, String folder) {
        try {
            String fileName = buildFileName(file.getOriginalFilename(), folder);

            ObjectMetadata metadata = buildMetadata(file.getSize(), file.getOriginalFilename(), file.getContentType());

            cosClient.putObject(new PutObjectRequest(
                    properties.getBucketName(),
                    fileName,
                    file.getInputStream(),
                    metadata
            ));

            return buildFileUrl(fileName);
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }

    /** 上传本地文件 */
    public String upload(File localFile, String folder) {
        try (FileInputStream fis = new FileInputStream(localFile)) {
            String fileName = buildFileName(localFile.getName(), folder);

            ObjectMetadata metadata = buildMetadata(localFile.length(), localFile.getName(), null);

            cosClient.putObject(new PutObjectRequest(
                    properties.getBucketName(),
                    fileName,
                    fis,
                    metadata
            ));

            return buildFileUrl(fileName);
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }

    /** 删除文件 */
    public void delete(String fileKey) {
        try {
            cosClient.deleteObject(new DeleteObjectRequest(properties.getBucketName(), fileKey));
        } catch (Exception e) {
            throw new RuntimeException("删除文件失败: " + fileKey, e);
        }
    }

    /** 构建文件名：UUID + 后缀，自动加文件夹前缀 */
    private String buildFileName(String originalName, String folder) {
        String suffix = "";
        if (originalName != null && originalName.contains(".")) {
            suffix = originalName.substring(originalName.lastIndexOf("."));
        }
        String fileName = UUID.randomUUID() + suffix;
        return (folder == null || folder.isEmpty()) ? fileName : folder + "/" + fileName;
    }

    /** 构建元信息 */
    private ObjectMetadata buildMetadata(long size, String originalName, String contentType) {
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(size);
        if (contentType == null || "application/octet-stream".equals(contentType)) {
            contentType = getContentType(originalName);
        }
        metadata.setContentType(contentType);
        metadata.setHeader("Content-Disposition", "inline");
        return metadata;
    }

    /** 拼接访问 URL */
    private String buildFileUrl(String fileName) {
        return String.format("https://%s.cos.%s.myqcloud.com/%s",
                properties.getBucketName(),
                properties.getRegion(),
                fileName);
    }

    /** 根据文件后缀推断 ContentType */
    private String getContentType(String filename) {
        if (filename == null || !filename.contains(".")) return "application/octet-stream";
        String ext = filename.substring(filename.lastIndexOf(".")).toLowerCase();
        return switch (ext) {
            case ".jpg", ".jpeg" -> "image/jpeg";
            case ".png" -> "image/png";
            case ".gif" -> "image/gif";
            case ".webp" -> "image/webp";
            case ".svg" -> "image/svg+xml";
            case ".pdf" -> "application/pdf";
            case ".mp4" -> "video/mp4";
            case ".mp3" -> "audio/mpeg";
            default -> "application/octet-stream";
        };
    }
}
